package services

import (
	"hg/enmu"
	"hg/models"
	"hg/pkg/database"
	"hg/utils"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// 注册函数
func RegisterPostService(c *gin.Context) {
	user := new(models.Userinfo)
	resp := models.GetDefaultResp()
	if err := c.ShouldBindJSON(&user); err != nil {
		setApiError(c, http.StatusInternalServerError, resp, err)
		return
	}
	if register(user.Username, user.Password) {
		c.JSON(http.StatusOK, resp)
	} else {
		resp.Code, resp.Msg = enmu.BAD_REGIRSTER_INFO_CODE, enmu.BAD_REGIRSTER_INFO_MSG 
		c.JSON(http.StatusBadRequest,resp)
	}
}

func register(username, password string) bool {
	user := &models.Userinfo{Username: username}
	hashedPassword := utils.HashPassword(password, username)
	user.Password = hashedPassword
	err := database.InsertOneUser(user)
	if err != nil {
		logrus.Errorln("insert register user error : ", err)
		return false
	}
	return true
}
